package com.lzh.gulimall.seckill.config;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.alibaba.fastjson.JSON;
import com.lzh.common.exception.BizCodeEnum;
import com.lzh.common.utils.R;
import com.lzh.gulimall.seckill.interceptor.LoginUserInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @ClassName SeckillWebConfig
 * @Description TODO
 * @Author liuzhihui
 * @Date 2020/9/10 15:43
 * @Version 1.0
 **/
@Configuration
public class SeckillWebConfig implements WebMvcConfigurer {
    @Autowired
    private LoginUserInterceptor loginUserInterceptor;
    @Autowired
    private SentinelWebInterceptor sentinelWebInterceptor;

    /**
     * 添加拦截器
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(sentinelWebInterceptor).addPathPatterns("/**");
        registry.addInterceptor(loginUserInterceptor).addPathPatterns("/**");
    }

    /**
     * 自定义流控响应
     * @return
     */
    @Bean
    public SentinelWebInterceptor sentinelWebInterceptor(){
        SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig();
        sentinelWebMvcConfig.setBlockExceptionHandler((request, response, e) -> {
            R error = R.error(BizCodeEnum.TOO_MANY_REQUEST.getCode(), BizCodeEnum.TOO_MANY_REQUEST.getMessage());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(error));
        });
        return  new SentinelWebInterceptor(sentinelWebMvcConfig);
    }
}
